<template>
  <div class="meeting-detail-container">
    <div class="header">
      <button class="back-btn" @click="goBack">← 返回列表</button>
      <h1>{{ meeting.title }}</h1>
    </div>
    
    <div class="meeting-info">
      <div class="info-item">
        <span class="label">描述：</span>
        <span class="value">{{ meeting.description || '无描述' }}</span>
      </div>
      <div class="info-item">
        <span class="label">状态：</span>
        <span :class="`status-badge status-${meeting.status.toLowerCase()}`">
          {{ getStatusText(meeting.status) }}
        </span>
      </div>
      <div class="info-item">
        <span class="label">文件：</span>
        <span class="value">{{ meeting.file_name || '无文件' }}</span>
      </div>
      <div class="info-item">
        <span class="label">创建时间：</span>
        <span class="value">{{ formatDate(meeting.created_at) }}</span>
      </div>
      <div class="info-item">
        <span class="label">更新时间：</span>
        <span class="value">{{ formatDate(meeting.updated_at) }}</span>
      </div>
    </div>
    
    <!-- 音频播放控制 -->
    <div v-if="meeting.transcription_result && meeting.transcription_result.audio_duration" class="audio-player">
      <div class="audio-controls">
        <button class="play-btn" @click="togglePlayback" :title="isPlaying ? '暂停' : '播放'">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </button>
        <div class="time-display">
          {{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}
        </div>
        <div class="progress-bar-container">
          <div 
            class="progress-bar"
            @click="seek"
          >
            <div 
              class="progress"
              :style="{ width: `${progressPercentage}%` }"
            ></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 转录结果 -->
    <div v-if="meeting.transcription_result" class="transcription-container">
      <h2>转录结果</h2>
      
      <!-- 完整转录文本 -->
      <div v-if="meeting.transcription_result.text" class="full-text">
        <h3>完整文本</h3>
        <div class="text-content">
          {{ meeting.transcription_result.text }}
        </div>
      </div>
      
      <!-- 段落转录结果 -->
      <div v-if="meeting.transcription_result.segments && meeting.transcription_result.segments.length > 0" class="segments-container">
        <h3>分段文本</h3>
        <div class="segments-list">
          <div 
            v-for="(segment, index) in meeting.transcription_result.segments" 
            :key="index"
            class="segment-item"
            :class="{ 'active': isSegmentActive(index) }"
            @click="playSegment(segment, index)"
            :title="`${formatTime(segment.start_time)} - ${formatTime(segment.end_time)}`"
          >
            <div class="segment-header">
              <span class="speaker" v-if="segment.speaker_id">
                {{ segment.speaker_id }}
              </span>
              <span class="segment-time">
                {{ formatTime(segment.start_time) }} - {{ formatTime(segment.end_time) }}
              </span>
            </div>
            <div class="segment-text">
              {{ segment.text }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 处理信息 -->
      <div class="processing-info">
        <p>音频时长：{{ formatTime(meeting.transcription_result.audio_duration) }}</p>
        <p>处理时间：{{ meeting.transcription_result.processing_time.toFixed(2) }}秒</p>
      </div>
    </div>
    
    <!-- 处理中状态 -->
    <div v-else-if="meeting.status === 'PROCESSING'" class="processing-state">
      <div class="loading-spinner"></div>
      <p>正在处理录音，请稍候...</p>
      <p class="processing-hint">处理时间取决于录音长度，可能需要几分钟</p>
    </div>
    
    <!-- 失败状态 -->
    <div v-else-if="meeting.status === 'FAILED'" class="error-state">
      <div class="error-icon">❌</div>
      <p>录音处理失败</p>
      <p class="error-hint">请检查文件格式是否正确，或尝试重新上传</p>
      <button class="retry-btn" @click="retryProcessing">重新处理</button>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>暂无转录结果</p>
      <p class="empty-hint">请上传录音文件进行转录</p>
    </div>
    
    <!-- 操作按钮 -->
    <div class="actions">
      <button class="edit-btn" @click="editMeeting">编辑会议</button>
      <button class="delete-btn" @click="deleteMeeting">删除会议</button>
    </div>
    
    <!-- 编辑会议对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog" @click.stop>
        <h3>编辑会议</h3>
        <div class="form-group">
          <label for="edit-meeting-title">会议标题</label>
          <input 
            id="edit-meeting-title"
            v-model="editMeetingTitle"
            type="text"
            placeholder="请输入会议标题"
          />
        </div>
        <div class="form-group">
          <label for="edit-meeting-description">会议描述</label>
          <textarea 
            id="edit-meeting-description"
            v-model="editMeetingDescription"
            placeholder="请输入会议描述"
            rows="3"
          ></textarea>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="closeEditDialog">取消</button>
          <button 
            class="confirm-btn" 
            @click="submitEditMeeting"
            :disabled="!editMeetingTitle.trim()"
          >
            保存
          </button>
        </div>
      </div>
    </div>
    
    <!-- 隐藏的音频元素 -->
    <audio 
      ref="audioElement"
      @timeupdate="updateTime"
      @ended="onPlaybackEnded"
      preload="metadata"
    ></audio>
  </div>
</template>

<script>
export default {
  name: 'MeetingDetail',
  data() {
    return {
      meeting: {
        id: null,
        title: '',
        description: '',
        status: '',
        created_at: '',
        updated_at: '',
        file_name: '',
        transcription_result: null
      },
      isLoading: true,
      isPlaying: false,
      currentTime: 0,
      totalDuration: 0,
      progressPercentage: 0,
      activeSegmentIndex: -1,
      showEditDialog: false,
      editMeetingTitle: '',
      editMeetingDescription: ''
    }
  },
  async mounted() {
    // 获取URL中的会议ID
    const meetingId = this.$route.params.id
    await this.fetchMeetingDetail(meetingId)
  },
  methods: {
    async fetchMeetingDetail(meetingId) {
      try {
        const response = await fetch(`/api/v1/meetings/${meetingId}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        })
        
        if (!response.ok) {
          throw new Error('获取会议详情失败')
        }
        
        const data = await response.json()
        this.meeting = data
        
        // 如果有转录结果和音频时长，设置总时长
        if (data.transcription_result && data.transcription_result.audio_duration) {
          this.totalDuration = data.transcription_result.audio_duration
        }
        
      } catch (error) {
        console.error('获取会议详情错误:', error)
        alert('获取会议详情失败，请重试')
        this.goBack()
      } finally {
        this.isLoading = false
      }
    },
    
    goBack() {
      this.$router.push('/meetings')
    },
    
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待处理',
        'PROCESSING': '处理中',
        'COMPLETED': '已完成',
        'FAILED': '失败'
      }
      return statusMap[status] || status
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    },
    
    togglePlayback() {
      const audio = this.$refs.audioElement
      if (audio) {
        if (this.isPlaying) {
          audio.pause()
        } else {
          // 模拟播放（实际应用中应该设置src并调用play）
          audio.currentTime = this.currentTime
          // audio.src = 'path/to/audio.mp3'  // 实际音频路径
          // audio.play()
          this.isPlaying = true
        }
      }
    },
    
    updateTime() {
      const audio = this.$refs.audioElement
      if (audio) {
        // 模拟时间更新（实际应用中应该使用audio.currentTime）
        if (this.isPlaying) {
          this.currentTime += 0.1
          if (this.currentTime >= this.totalDuration) {
            this.onPlaybackEnded()
            return
          }
        }
        
        this.progressPercentage = (this.currentTime / this.totalDuration) * 100
        
        // 更新当前活动段落
        this.updateActiveSegment()
      }
    },
    
    onPlaybackEnded() {
      this.isPlaying = false
      this.currentTime = 0
      this.progressPercentage = 0
      this.activeSegmentIndex = -1
    },
    
    seek(event) {
      const container = event.currentTarget
      const rect = container.getBoundingClientRect()
      const position = (event.clientX - rect.left) / rect.width
      this.currentTime = position * this.totalDuration
      this.progressPercentage = position * 100
      
      // 更新活动段落
      this.updateActiveSegment()
      
      // 如果正在播放，继续播放
      if (this.isPlaying) {
        const audio = this.$refs.audioElement
        if (audio) {
          audio.currentTime = this.currentTime
          // audio.play()
        }
      }
    },
    
    playSegment(segment, index) {
      this.currentTime = segment.start_time
      this.progressPercentage = (this.currentTime / this.totalDuration) * 100
      this.activeSegmentIndex = index
      
      // 开始播放
      const audio = this.$refs.audioElement
      if (audio) {
        // audio.currentTime = this.currentTime
        // audio.play()
        this.isPlaying = true
      }
    },
    
    updateActiveSegment() {
      if (!this.meeting.transcription_result || !this.meeting.transcription_result.segments) {
        return
      }
      
      for (let i = 0; i < this.meeting.transcription_result.segments.length; i++) {
        const segment = this.meeting.transcription_result.segments[i]
        if (this.currentTime >= segment.start_time && this.currentTime < segment.end_time) {
          this.activeSegmentIndex = i
          return
        }
      }
      
      // 如果没有找到匹配的段落，清除活动段落索引
      this.activeSegmentIndex = -1
    },
    
    isSegmentActive(index) {
      return this.activeSegmentIndex === index
    },
    
    editMeeting() {
      this.editMeetingTitle = this.meeting.title
      this.editMeetingDescription = this.meeting.description || ''
      this.showEditDialog = true
    },
    
    closeEditDialog() {
      this.showEditDialog = false
    },
    
    async submitEditMeeting() {
      if (!this.editMeetingTitle.trim()) {
        alert('请输入会议标题')
        return
      }
      
      try {
        const response = await fetch(`/api/v1/meetings/${this.meeting.id}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            title: this.editMeetingTitle,
            description: this.editMeetingDescription
          })
        })
        
        if (!response.ok) {
          throw new Error('更新会议失败')
        }
        
        // 刷新会议详情
        await this.fetchMeetingDetail(this.meeting.id)
        
        this.closeEditDialog()
        alert('会议信息已更新')
      } catch (error) {
        console.error('更新会议错误:', error)
        alert('更新会议失败，请重试')
      }
    },
    
    async deleteMeeting() {
      if (!confirm('确定要删除这个会议吗？')) {
        return
      }
      
      try {
        const response = await fetch(`/api/v1/meetings/${this.meeting.id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        })
        
        if (!response.ok) {
          throw new Error('删除会议失败')
        }
        
        // 删除成功后返回会议列表
        this.$router.push('/meetings')
      } catch (error) {
        console.error('删除会议错误:', error)
        alert('删除会议失败，请重试')
      }
    },
    
    async retryProcessing() {
      if (!confirm('确定要重新处理这个会议吗？')) {
        return
      }
      
      try {
        // 更新会议状态为处理中
        const response = await fetch(`/api/v1/meetings/${this.meeting.id}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            status: 'PROCESSING'
          })
        })
        
        if (!response.ok) {
          throw new Error('更新会议状态失败')
        }
        
        // 刷新会议详情
        await this.fetchMeetingDetail(this.meeting.id)
        alert('已开始重新处理，请稍候查看结果')
      } catch (error) {
        console.error('重新处理会议错误:', error)
        alert('重新处理会议失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.meeting-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  font-size: 16px;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.meeting-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #666;
  margin-right: 10px;
}

.value {
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #FFF3CD;
  color: #856404;
}

.status-processing {
  background-color: #E3F2FD;
  color: #1565C0;
}

.status-completed {
  background-color: #D4EDDA;
  color: #155724;
}

.status-failed {
  background-color: #F8D7DA;
  color: #721C24;
}

.audio-player {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.audio-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.play-btn {
  width: 40px;
  height: 40px;
  border: none;
  background-color: #2196F3;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-btn:hover {
  background-color: #1976D2;
}

.time-display {
  min-width: 100px;
  font-size: 14px;
  color: #666;
}

.progress-bar-container {
  flex: 1;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #ddd;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #2196F3;
  border-radius: 4px;
  transition: width 0.1s ease;
}

.transcription-container {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.transcription-container h2 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.transcription-container h3 {
  margin-top: 20px;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.full-text {
  margin-bottom: 20px;
}

.text-content {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.segments-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.segment-item {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.segment-item:hover {
  border-color: #2196F3;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.segment-item.active {
  border-color: #2196F3;
  background-color: #E3F2FD;
}

.segment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.speaker {
  padding: 4px 8px;
  background-color: #2196F3;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.segment-time {
  font-size: 12px;
  color: #666;
}

.segment-text {
  line-height: 1.5;
  color: #333;
}

.processing-info {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ddd;
  font-size: 14px;
  color: #666;
}

.processing-info p {
  margin: 5px 0;
}

.processing-state, .error-state, .empty-state {
  text-align: center;
  padding: 40px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2196F3;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.processing-hint, .error-hint, .empty-hint {
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.retry-btn {
  padding: 10px 20px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 20px;
}

.retry-btn:hover {
  background-color: #1976D2;
}

.actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.edit-btn, .delete-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.edit-btn {
  background-color: #FF9800;
  color: white;
}

.edit-btn:hover {
  background-color: #F57C00;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  min-width: 400px;
}

.dialog h3 {
  margin-top: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-btn {
  background-color: #4CAF50;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.confirm-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>